/**
 * @author Aaron
 * @createTime 10:12 2022/5/17
 **/
package db_main

import (
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

/**
 * @author Aaron
 * @description 用户根据任务ID领取奖励
 * @createTime 13:12 2022/5/18
 **/
func GetTaskRewardById(id uint8) ([]*api_models.TaskRewardListById, error) {
	fName := "GetTaskRewardById"
	var o []*api_models.TaskRewardListById
	err := mysql.GetRTable(&models_main.TaskReward{}).
		Select("db_task_reward.*,db_gift.icon as icon,"+
			"if(db_task_reward.reward_type = 3, db_gift.title,if(db_task_reward.reward_type = 5, db_props_new.name, '')) as title").
		Joins("left join models_live.db_gift on db_gift.id=db_task_reward.gift_id").
		Joins("left join db_props_new on db_props_new.id=db_task_reward.props_id").
		Where("task_id = ?", id).
		Find(&o).
		Error
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	return o, nil
}

func GetTaskRewardById2(id uint8) ([]*api_models.TaskRewardListById, error) {
	fName := "GetTaskRewardById"
	var (
		err         error
		gift_ids    []uint16
		gifts       []*models_main.Gift
		taskRewards []*models_main.TaskReward
		result      []*api_models.TaskRewardListById
	)

	// TODO 缓存

	if err = mysql.GetRTable(&models_main.TaskReward{}).
		Select("*").
		Where("task_id = ?", id).
		Find(&taskRewards).Error; err != nil {
		return nil, fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}

	if len(taskRewards) > 0 {
		for _, reward := range taskRewards {
			gift_ids = append(gift_ids, reward.GiftId)
		}
	}
	if len(gift_ids) > 0 {
		if err = global.Live().Model(&models_main.Gift{}).
			Select("*").
			Where("id IN ?", gift_ids).
			Find(&gifts).Error; err != nil {
			return nil, fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
		}
	}

	get_gift := func(gid int) *models_main.Gift {
		if gid == 0 || len(gifts) == 0 {
			return &models_main.Gift{}
		}

		for _, gift := range gifts {
			if gift.Id == gid {
				return gift
			}
		}

		return &models_main.Gift{}
	}

	for _, reward := range taskRewards {
		gift := get_gift(int(reward.GiftId))
		result = append(result, &api_models.TaskRewardListById{
			RewardType: reward.RewardType, //0-经验,1-鹰钻 2-克拉 3-礼物 4-道具
			GiftId:     reward.GiftId,
			Icon:       gift.Icon,
			Title:      gift.Title,
			Quantity:   reward.Quantity, //数量
			PriceType:  gift.PriceType,  //1-毒液 2-金坷拉
		})
	}

	return result, nil
}

/**
 * @author Aaron
 * @description
 * @createTime 13:56 2022/5/18
 **/
func GetTaskRewardListByIds(ids []uint8) ([]*api_models.GetTaskRewardList, error) {
	// 此方法废弃，db_gift表和db_task_reward表已拆到不同到数据库中
	fName := "GetTaskRewardListByIds"
	var o []*api_models.GetTaskRewardList
	err := mysql.GetRTable(&models_main.TaskReward{}).
		Raw(fmt.Sprintf(`
			SELECT
				db_task_reward.*,
				db_gift.icon AS icon,
				db_gift.title AS title 
			FROM
				db_task_reward
				LEFT JOIN models_live.db_gift ON db_gift.id = db_task_reward.gift_id WHERE task_id IN %s`,
			utils2.QueryUint8Slice2Str(ids))).
		Find(&o).
		Error
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	return o, nil
}

func GetTaskRewardListByIds2(ids []uint8) ([]*api_models.GetTaskRewardList, error) {
	var (
		err         error
		giftIDs     []uint8
		fName       = "GetTaskRewardListByIds2"
		gifts       []*models_main.Gift
		taskRewards []*models_main.TaskReward
		result      []*api_models.GetTaskRewardList
	)

	// 取任务奖励关联表数据
	if mysql.GetRTable(&models_main.TaskReward{}).
		Raw(fmt.Sprintf(`
			SELECT * FROM db_task_reward WHERE task_id IN %s`, utils2.QueryUint8Slice2Str(ids))).
		Find(&taskRewards).Error != nil {
		return nil, fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}

	for _, reward := range taskRewards {
		if reward.GiftId > 0 {
			giftIDs = append(giftIDs, uint8(reward.GiftId))
		}
	}

	if len(giftIDs) == 0 {
		goto OUTPUT
	}

	err = global.Live().Model(&models_main.Gift{}).
		Raw(fmt.Sprintf(`
			SELECT *
			FROM db_gift WHERE id IN %s`,
			utils2.QueryUint8Slice2Str(giftIDs))).
		Find(&gifts).
		Error
	if err != nil {
		return nil, fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}

	for _, reward := range taskRewards {
		var item_gift *models_main.Gift
		for _, gift := range gifts {
			if int(reward.GiftId) == gift.Id {
				item_gift = gift
				break
			}
		}

		if item_gift == nil {
			item_gift = &models_main.Gift{}
		}

		result = append(result, &api_models.GetTaskRewardList{
			TaskId: reward.TaskId,
			TaskRewardListById: api_models.TaskRewardListById{
				RewardType: reward.RewardType,
				Quantity:   reward.Quantity,
				GiftId:     uint16(item_gift.Id),
				Icon:       item_gift.Icon,
				Title:      item_gift.Title,
			},
		})
	}

	return result, nil

OUTPUT:
	for _, reward := range taskRewards {
		result = append(result, &api_models.GetTaskRewardList{
			TaskId: reward.TaskId,
			TaskRewardListById: api_models.TaskRewardListById{
				RewardType: reward.RewardType,
				Quantity:   reward.Quantity,
				GiftId:     0,
				Icon:       "",
				Title:      "",
			},
		})
	}

	return result, nil
}

func GetTaskRewardListByIds3(ids []uint8) ([]*api_models.GetTaskRewardList, error) {
	fName := "GetTaskRewardById"
	var o []*api_models.GetTaskRewardList
	if len(ids) <= 0 {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), "taskIds不能为空")
	}
	err := mysql.GetRTable(&models_main.TaskReward{}).
		Select("db_task_reward.*,db_gift.icon as icon," +
			"if(db_task_reward.reward_type = 3, db_gift.title,if(db_task_reward.reward_type = 5, db_props_new.name, '')) as title").
		Joins("left join models_live.db_gift on db_gift.id=db_task_reward.gift_id").
		Joins("left join db_props_new on db_props_new.id=db_task_reward.props_id").
		Where(fmt.Sprintf("task_id in %s", utils2.QueryUint8Slice2Str(ids))).
		Find(&o).
		Error
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	return o, nil
}
